package net.betou.trade.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.betou.common.web.ResponseUtils;
import net.sf.json.JSONObject;


/**
 * 主要针对页面ajax消息返回消息
 * @author 叶装装
 *
 */
public class ResponseUtil{

	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String WARN = "warn";
	
	private Map< String, String > jsonMap;
	private HttpServletResponse response;
	
	public static ResponseUtil create( HttpServletResponse response ){
		return new ResponseUtil( response );
	}
	
	public boolean hasResponse( ){
		return !jsonMap.isEmpty( );
	}
	
	/**
	 * 该构造不应被调用，写下只是习惯
	 */
	public ResponseUtil( ){
	}
	
	public ResponseUtil( HttpServletResponse response ){
		jsonMap = new HashMap< String, String >( );
		this.response = response;
	}
	
	public void addResponse( String type, String content ){
		jsonMap.put( "type", type );
		jsonMap.put( "content", content );
	}
	
	/**
	 * 添加成功消息
	 * @param content
	 */
	public void addSuccessResponse( String content ){
		addResponse( SUCCESS, content );
	}
	
	/**
	 * 警告消息
	 * @param content
	 */
	public void addWarnResponse( String content ){
		addResponse( WARN, content );
	}
	
	/**
	 * 错误消息
	 * @param content
	 */
	public void addErrorResponse( String content ){
		addResponse( ERROR, content );
	}
	
	/**
	 * 返回json消息
	 */
	public void renderJson( ){
		JSONObject obj = JSONObject.fromObject( jsonMap );
		ResponseUtils.renderJson( response, obj.toString( ) );
	}
}
